// var config = require('../../../utils/config.js');
// var http = require('../../../utils/request.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabs: [{ft_name: "推荐",ft_id: "a"},
    {ft_name: "游乐项目",ft_id: "b"},
    {ft_name: "演出表演",ft_id: "c"},
    {ft_name: "文创商店",ft_id: "d"},
    {ft_name: "美食餐厅",ft_id: "e"},
    {ft_name: "精选酒店",ft_id: "f"},
    {ft_name: "游客服务",ft_id: "g"}],
    tabsList: [
            {ft_id: "a",f_Cooks_Id:'11',food_Img:'https://www.universalbeijingresort.com/sites/default/files/2021-09/detailpage2.png',f_Name:'哈利·波特的魔法世界',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'非常好玩，非常推荐。',si_imgUrl:[{pic_Url:'https://www.universalbeijingresort.com/sites/default/files/2021-09/detailpage2.png'},{pic_Url:'https://www.universalbeijingresort.com/sites/default/files/2021-09/detailpage2.png'}]},
            {ft_id: "a",f_Cooks_Id:'12',food_Img:'https://bkimg.cdn.bcebos.com/pic/bf096b63f6246b600c3338aa9ba80d4c510fd8f90496?x-bce-process=image/watermark,image_d2F0ZXIvYmFpa2UxNTA=,g_7,xp_5,yp_5',f_Name:'变形金刚基地',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'',si_imgUrl:[{pic_Url:''},{pic_Url:' '}]},
            {ft_id: "b",f_Cooks_Id:'13',food_Img:'https://bkimg.cdn.bcebos.com/pic/a686c9177f3e6709c93d44204b97883df8dcd000ff96?x-bce-process=image/watermark,image_d2F0ZXIvYmFpa2UxNTA=,g_7,xp_5,yp_5',f_Name:'功夫熊猫盖世之地',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'',si_imgUrl:[{pic_Url:' '},{pic_Url:' '}]},
            {ft_id: "b",f_Cooks_Id:'14',food_Img:'https://bkimg.cdn.bcebos.com/pic/30adcbef76094b36acafc232d39c6bd98d1000e937e9?x-bce-process=image/watermark,image_d2F0ZXIvYmFpa2UyMjA=,g_7,xp_5,yp_5',f_Name:'好莱坞',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'',si_imgUrl:[{pic_Url:' '},{pic_Url:' '}]},
			{ft_id: "c",f_Cooks_Id:'15',food_Img:'https://www.universalbeijingresort.com/sites/default/files/2021-09/WaterWorld%20Stunt%20Show3.jpg',f_Name:'未来水世界特技表演',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'',si_imgUrl:[{pic_Url:''},{pic_Url:''}]},
			{ft_id: "c",f_Cooks_Id:'16',food_Img:'https://www.universalbeijingresort.com/sites/default/files/2021-09/The%20Nighttime%20Lights%20at%20the%20Hogwarts%E2%84%A2%20Castle1.jpg',f_Name:'霍格沃茨™城堡夜间魔法庆典',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'',si_imgUrl:[{pic_Url:' '},{pic_Url:' '}]},
            {ft_id: "d",f_Cooks_Id:'17',food_Img:'https://www.universalbeijingresort.com/sites/default/files/2021-05/USS%20_1.jpg',f_Name:'环球影城商店',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'',si_imgUrl:[{pic_Url:' '},{pic_Url:' '}]},
			{ft_id: "d",f_Cooks_Id:'18',food_Img:'https://www.universalbeijingresort.com/sites/default/files/2021-09/Minion%20Mart1.jpg',f_Name:'小黄人集市',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'',si_imgUrl:[{pic_Url:' '},{pic_Url:' '}]},
			{ft_id: "e",f_Cooks_Id:'19',food_Img:'https://www.universalbeijingresort.com/sites/default/files/2021-07/Sunset%20Grill%20Cover%20%283%29.jpg',f_Name:'落霞餐厅',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'',si_imgUrl:[{pic_Url:' '},{pic_Url:' '}]},
			{ft_id: "e",f_Cooks_Id:'20',food_Img:'https://www.universalbeijingresort.com/sites/default/files/2021-07/Grandma%20Panda%27s%20Kitchen1080x600.png',f_Name:'熊猫婆婆私房菜',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'',si_imgUrl:[{pic_Url:' '},{pic_Url:' '}]},
			{ft_id: "f",f_Cooks_Id:'21',food_Img:'https://www.universalbeijingresort.com/sites/default/files/2021-04/NUO-min_0.jpg',f_Name:'诺金度假酒店',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'',si_imgUrl:[{pic_Url:' '},{pic_Url:' '}]},
			{ft_id: "f",f_Cooks_Id:'22',food_Img:'https://www.universalbeijingresort.com/sites/default/files/2021-04/USGH-min_0.jpg',f_Name:'环球影城大酒店',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'',si_imgUrl:[{pic_Url:' '},{pic_Url:' '}]},
			{ft_id: "g",f_Cooks_Id:'23',food_Img:'https://www.universalbeijingresort.com/sites/default/files/2023-01/1080x600.jpg',f_Name:'私家车停车',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'',si_imgUrl:[{pic_Url:' '},{pic_Url:' '}]},
            {ft_id: "g",f_Cooks_Id:'24',food_Img:'https://www.universalbeijingresort.com/sites/default/files/2023-01/1080x600_3.jpg',f_Name:'公交车上客区',f_Description:'真的很好玩，推荐！',f_DPrice:'12',f_Price:'18',quantity:'0',f_Introduction:'',si_imgUrl:[{pic_Url:' '},{pic_Url:' '}]}],
    indexId: 0,
    toTitle: "title-0",
    scrollTop: 0,
    top: [],
    totalPrice: 0, //选中商品总价格
    totalNum: 0, //选中商品数量
    cartList: [], //选中商品列表
    // 购物车动画
    animationData: {},
    animationMask: {},
    maskVisual: "hidden",
    maskFlag: true,
  },
  // 左侧点击事件
  jumpIndex(e) {
    let index = e.currentTarget.dataset.menuindex;
    let ft_id = e.currentTarget.dataset.ft_id;
    let that = this
    that.setData({
      indexId: index,
      toTitle: "title-" + ft_id
    });
  },
  scrollToLeft(res) {
    console.log("scrollToLeft-res:" + JSON.stringify(res) + JSON.stringify(this.data.top));
    this.setData({
      scrollTop: res.detail.scrollTop
    })
    var length = this.data.top.length;
    for (var i = 0; i < this.data.top.length; i++) {
      if (this.data.top[i] - this.data.top[0] <= this.data.scrollTop && (i < length - 1 && this.data.top[i + 1] - this.data.top[0] > this.data.scrollTop)) {
        if (this.data.indexId != i) {
          this.setData({
            indexId: i,
          });
        }
      }
    }
  },
  onLoad: async function (options) {
    console.log(this.data.tabsList)
    var that = this;
    wx.showLoading({
      mask: true,
      title: '加载中…',
    })
    // //获取分类
    // await GetFoodType(that)
    // //获取景点
    // await GetFoodCook(that)
    wx.hideLoading()
    console.log(that.data.tabsList)
    //赋值
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winHeight: res.windowHeight - 100
        });
        var top2 = new Array();
        for (var i = 0; i < that.data.tabs.length; i++) {
          wx.createSelectorQuery().select('#view-' + that.data.tabs[i].ft_id).boundingClientRect(function (rect) {
            var isTop = Number(rect.top);
            top2.push(isTop);
            console.log("view-c:" + JSON.stringify(rect));
          }).exec();
        }
        that.setData({
          top: top2
        });
      }
    });
    this.onShow()
  },
  onShow: function (options) {
    var that = this;
    // 获取购物车缓存数据
    var arr = wx.getStorageSync('cart') || [];
    // 进入页面后判断购物车是否有数据，如果有，将菜单与购物车quantity数据统一
    if (arr.length > 0) {
      for (var j in that.data.tabsList) {
      for (var i in arr) {
          if (that.data.tabsList[j].f_Cooks_Id == arr[i].f_Cooks_Id) {
            that.data.tabsList[j].quantity = arr[i].quantity;
            break
          } else {
            that.data.tabsList[j].quantity = 0;
          }
        }
      }
    } else {
      for (var j in that.data.tabsList) {
        that.data.tabsList[j].quantity = 0;
      }
    }
    // 进入页面计算购物车总价、总数
    var totalPrice = 0;
    var totalNum = 0;
    if (arr.length > 0) {
      for (var i in arr) {
        totalPrice += arr[i].f_DPrice * arr[i].quantity;
        totalNum += Number(arr[i].quantity);
      }
    }
    // 赋值数据
    this.setData({
      cartList: arr,
      tabsList: that.data.tabsList,
      totalPrice: totalPrice,
      totalNum: totalNum
    })
  },
  // 购物车增加数量
  addCart: function (e) {
    var id = e.currentTarget.dataset.id;
    var arr = wx.getStorageSync('cart') || [];
    var f = false;
    for (var i in this.data.tabsList) { // 遍历菜单找到被点击的菜品，数量加1
      if (this.data.tabsList[i].f_Cooks_Id == id) {
        this.data.tabsList[i].quantity += 1;
        if (arr.length > 0) {
          for (var j in arr) { // 遍历购物车找到被点击的菜品，数量加1
            if (arr[j].f_Cooks_Id == id) {
              arr[j].quantity += 1;
              f = true;
              try {
                wx.setStorageSync('cart', arr)
              } catch (e) {
                console.log(e)
              }
              break;
            }
          }
          if (!f) {
            arr.push(this.data.tabsList[i]);
          }
        } else {
          arr.push(this.data.tabsList[i]);
        }
        try {
          wx.setStorageSync('cart', arr)
        } catch (e) {
          console.log(e)
        }
        break;
      }
    }
    this.setData({
      cartList: arr,
      tabsList: this.data.tabsList
    })
    this.getTotalPrice();
  },
  // 购物车减少数量
  delCart: function (e) {
    var id = e.currentTarget.dataset.id;
    var arr = wx.getStorageSync('cart') || [];
    for (var i in this.data.tabsList) {
      if (this.data.tabsList[i].f_Cooks_Id == id) {
        this.data.tabsList[i].quantity -= 1;
        if (this.data.tabsList[i].quantity <= 0) {
          this.data.tabsList[i].quantity = 0;
        }
        if (arr.length > 0) {
          for (var j in arr) {
            if (arr[j].f_Cooks_Id == id) {
              arr[j].quantity -= 1;
              if (arr[j].quantity <= 0) {
                this.removeByValue(arr, id) //77
              }
              if (arr.length <= 0) {
                this.setData({
                  tabsList: this.data.tabsList,
                  cartList: [],
                  totalNum: 0,
                  totalPrice: 0,
                })
                this.cascadeDismiss()
              }
              try {
                wx.setStorageSync('cart', arr)
              } catch (e) {
                console.log(e)
              }
            }
          }
        }
      }
    }
    this.setData({
      cartList: arr,
      tabsList: this.data.tabsList
    })
    this.getTotalPrice();
  },
  // 定义根据id删除数组的方法
  removeByValue: function (array, val) {
    for (var i = 0; i < array.length; i++) {
      if (array[i].f_Cooks_Id == val) {
        array.splice(i, 1);
        break;
      }
    }
  },
  // 获取购物车总价、总数
  getTotalPrice: function () {
    var cartList = this.data.cartList; // 获取购物车列表
    var totalP = 0;
    var totalN = 0
    for (var i in cartList) { // 循环列表得到每个数据
      totalP += cartList[i].quantity * cartList[i].f_DPrice; // 所有价格加起来     
      totalN += cartList[i].quantity
    }
    this.setData({ // 最后赋值到data中渲染到页面
      cartList: cartList,
      totalNum: totalN,
      totalPrice: totalP
    });
  },
  // 清空购物车
  cleanList: function (e) {
    for (var t in this.data.tabs) {
      for (var j in this.data.tabsList) {
        this.data.tabsList[j].quantity = 0;
      }
    }
    try {
      wx.setStorageSync('cart', "")
    } catch (e) {
      console.log(e)
    }
    this.setData({
      tabsList: this.data.tabsList,
      cartList: [],
      cartFlag: false,
      totalNum: 0,
      totalPrice: 0,
    })
    this.cascadeDismiss()
  },
  //删除购物车单项
  deleteOne: function (e) {
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    var arr = wx.getStorageSync('cart')
    for (var i in this.data.tabsList) {
      if (this.data.tabsList[i].f_Cooks_Id == id) {
        this.data.tabsList[i].quantity = 0;
      }
    }
    arr.splice(index, 1);
    if (arr.length <= 0) {
      this.setData({
        tabsList: this.data.tabsList,
        cartList: [],
        cartFlag: false,
        totalNum: 0,
        totalPrice: 0,
      })
      this.cascadeDismiss()
    }
    try {
      wx.setStorageSync('cart', arr)
    } catch (e) {
      console.log(e)
    }
    this.setData({
      cartList: arr,
      tabsList: this.data.tabsList
    })
    this.getTotalPrice()
  },
  //切换购物车开与关
  cascadeToggle: function () {
    var that = this;
    var arr = this.data.cartList
    if (arr.length > 0) {
      if (that.data.maskVisual == "hidden") {
        that.cascadePopup()
      } else {
        that.cascadeDismiss()
      }
    } else {
      that.cascadeDismiss()
    }

  },
  // 打开购物车方法
  cascadePopup: function () {
    var that = this;
    // 购物车打开动画
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-in-out',
      delay: 0
    });
    that.animation = animation;
    animation.translate(0, -285).step();
    that.setData({
      animationData: that.animation.export(),
    });
    // 遮罩渐变动画
    var animationMask = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear',
    });
    that.animationMask = animationMask;
    animationMask.opacity(0.8).step();
    that.setData({
      animationMask: that.animationMask.export(),
      maskVisual: "show",
      maskFlag: false,
    });
  },
  // 关闭购物车方法
  cascadeDismiss: function () {
    var that = this
    // 购物车关闭动画
    that.animation.translate(0, 285).step();
    that.setData({
      animationData: that.animation.export()
    });
    // 遮罩渐变动画
    that.animationMask.opacity(0).step();
    that.setData({
      animationMask: that.animationMask.export(),
    });
    // 隐藏遮罩层
    that.setData({
      maskVisual: "hidden",
      maskFlag: true
    });
  },
  // 跳转确认订单页面
  gotoOrder: function () {
    wx.navigateTo({
      url: '../confirmOrder/confirmOrder'
    })
  },
  //跳转搜索
  searchNav: function () {
    wx.navigateTo({
      url: '/pages/search/search'
    });
  },
  toDetail: function (e) {
    var id = e.currentTarget.dataset.id;
    var goodDetail = [];
    for (var i = 0; i < this.data.tabsList.length; i++) {
      if (this.data.tabsList[i].f_Cooks_Id == id) {
        goodDetail.push(this.data.tabsList[i]);
      }
    }
    wx.navigateTo({
      url: '../../category/goodDetail/goodDetail?goodDetail=' + JSON.stringify(goodDetail),
    })
  },
  gotoOrder: function () {
    var count=wx.getStorageSync('cart').length
    console.log(count)
    if(count<=0){
      wx.showToast({
        title: '请先选择菜品',
        icon:"none"
      })
      return
    }
    wx.navigateTo({
      url: '../../category/previewOrder/previewOrder',
    })
  }
})
//获取商品信息
function GetFoodCook(_this) {
  var that = _this
  return new Promise((resove, reject) => {
    //获取分类
    let data = {
      CookName:""
    }
    let header = {}
    http.request(config.GetFoodCook_WXList, data, 'POST', header).then(function (res) {
      var e = res
      if (e.meta.Code == 200) {
        that.setData({
          tabsList: e.data.foodCookInfo == null ? [] : e.data.foodCookInfo
        })
        resove(true);
      } else {
        wx.showToast({
          title: res.Msg,
          duration: 2000,
          icon: "none",
          mask: true
        })
        reject(false)
      }
    }).catch((res) => {
      wx.showToast({
        title: res.Msg,
        duration: 2000,
        icon: "none",
        mask: true
      })
      reject(false)
    })
  })
}
//获取商品类别
function GetFoodType(_this) {
  var that = _this
  return new Promise((resove, reject) => {
    let data = {
      pagenum: 1,
      pagesize: 100
    }
    let header = {}
    http.request(config.GetFoodTypeList, data, 'POST', header).then(function (res) {
      var e = res
      if (e.meta.Code == 200) {
        that.setData({
          tabs: e.data.foodTypeInfo == null ? [] : e.data.foodTypeInfo
        })
        resove(true);
      } else {
        wx.showToast({
          title: res.Msg,
          duration: 2000,
          icon: "none",
          mask: true
        })
        reject(false)
      }
    }).catch((res) => {
      wx.showToast({
        title: res.Msg,
        duration: 2000,
        icon: "none",
        mask: true
      })
      reject(false)
    })
  })
}
